package com.base.api.cdr;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.api.pms.PmsPublicSqlQuery;
import com.base.utils.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.*;

/**
 * @author wnhuang
 * @Package com.base.api.cdr
 * @date 2020-12-23 21:45
 */
@Component
public class TestReportInfo extends PmsPublicSqlQuery {
    @Override
    public String splicSql(String sql, Map<String, Object> param) {
        StringBuilder param1 = new StringBuilder();
        if (param != null) {
            param1.append(" and patientID = '" + param.get("patientId") + "'");
            if(param.get("visitNumber") != null && !StringUtils.isBlank((String) (param.get("visitNumber")))){
                param1.append(" and visitNumber = '" + param.get("visitNumber") + "'");
            }
            return MessageFormat.format(sql.replace("'", "''"), param1.toString());
        } else {
            return "select 1 ";
        }
    }

    @Override
    public Map<String, Object> beforReturn(Map<String, Object> map) {
        List<Map<String, Object>> list = (List<Map<String, Object>>)map.get("Data");
        Map<String, Object> map1 = new HashMap<>();
        map1.put("Data", TreeUtil.listToTree(JSONArray.parseArray(JSONObject.toJSONString(toTree(list))), "label", "pid", "children"));
        map1.put("code", "0");
        return map1;
    }

    private List<Map<String, Object>> toTree(List<Map<String, Object>> list) {
        Set<Map<String, Object>> list2 = new HashSet<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map2 = new HashMap<>();
            String yyyy = (String)map.get("requestDateStr");
            map1.put("label",yyyy + map.get("opOrIp"));
            map1.put("pid","0");

            map2.put("label", map.get("ApplyId") + map.get("RequestItemName").toString());
            map2.put("pid", yyyy + map.get("opOrIp"));
            map2.put("requestDateTime",  map.get("requestDateTime"));
            map2.put("TypeName",  map.get("TypeName"));
            map2.put("RequestItemName",  map.get("RequestItemName"));
            map2.put("SpecimenSourceSiteName",  map.get("SpecimenSourceSiteName"));
            map.put("label",UUID.randomUUID());
            map.put("pid",map.get("ApplyId") + map.get("RequestItemName").toString());
            list2.add(map);
            list2.add(map1);
            list2.add(map2);
        }
        return new ArrayList<>(list2);
    }
}
